<template>
  <div class="tech-chart-container">
    <div ref="chartRef" class="chart-wrapper"></div>
    <div v-if="loading" class="chart-loading">
      <div class="loading-spinner"></div>
      <span>图表渲染中...</span>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick } from 'vue';
import { useEcharts } from '@/hooks/useEcharts';

const props = defineProps({
  // 图表类型
  type: {
    type: String,
    default: 'bar',
    validator: (value) => ['bar', 'line', 'pie', 'radar'].includes(value)
  },
  // 图表数据
  data: {
    type: [Object, Array],
    required: true
  },
  // 颜色主题
  colorTheme: {
    type: String,
    default: 'blue',
    validator: (value) => ['blue', 'purple', 'green', 'cyan'].includes(value)
  },
  // 加载状态
  loading: {
    type: Boolean,
    default: false
  }
});

const chartRef = ref(null);
const { initChart, updateOptions, isInitialized } = useEcharts(chartRef);

// 科技风颜色配置
const techColors = {
  blue: ['#00f2fe', '#4facfe'],
  purple: ['#667eea', '#764ba2'], 
  green: ['#43e97b', '#38f9d7'],
  cyan: ['#00d2ff', '#3a7bd5']
};

// 获取当前颜色主题
const currentTheme = techColors[props.colorTheme];

// 基础配置
const baseOptions = {
  backgroundColor: 'transparent',
  animation: true,
  animationDuration: 1000,
  animationEasing: 'cubicOut',
  grid: {
    left: '3%',
    right: '3%',
    bottom: '3%',
    top: '10%',
    containLabel: true
  }
};

// 工具提示配置
const tooltipConfig = {
  trigger: 'axis',
  axisPointer: {
    type: 'shadow',
    shadowStyle: {
      color: 'rgba(0, 242, 254, 0.1)'
    }
  },
  backgroundColor: 'rgba(10, 14, 23, 0.9)',
  borderColor: currentTheme[0],
  borderWidth: 1,
  textStyle: {
    color: '#e2e8f0'
  },
  extraCssText: 'box-shadow: 0 0 10px rgba(0, 242, 254, 0.3);'
};

// 坐标轴通用配置
const axisCommonConfig = {
  axisLine: {
    lineStyle: {
      color: currentTheme[0],
      width: 1
    }
  },
  axisLabel: {
    color: '#94a3b8',
    fontSize: 12
  },
  axisTick: {
    show: false
  }
};

// 不同类型图表的配置生成器
const chartConfigs = {
  bar: (data) => {
    const { categories = [], series = [] } = data;
    
    return {
      tooltip: tooltipConfig,
      xAxis: {
        type: 'category',
        data: categories,
        ...axisCommonConfig
      },
      yAxis: {
        type: 'value',
        ...axisCommonConfig,
        splitLine: {
          lineStyle: {
            color: 'rgba(79, 172, 254, 0.2)',
            type: 'dashed'
          }
        }
      },
      series: series.map((seriesItem, index) => ({
        name: seriesItem.name || `系列${index + 1}`,
        type: 'bar',
        data: seriesItem.data || [],
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: currentTheme[0]
            }, {
              offset: 1,
              color: currentTheme[1]
            }]
          },
          borderRadius: [2, 2, 0, 0],
          shadowColor: currentTheme[0],
          shadowBlur: 10
        },
        emphasis: {
          itemStyle: {
            shadowColor: currentTheme[0],
            shadowBlur: 20
          }
        }
      }))
    };
  },

  line: (data) => {
    const { categories = [], series = [] } = data;
    
    return {
      tooltip: tooltipConfig,
      xAxis: {
        type: 'category',
        data: categories,
        ...axisCommonConfig
      },
      yAxis: {
        type: 'value',
        ...axisCommonConfig,
        splitLine: {
          lineStyle: {
            color: 'rgba(79, 172, 254, 0.2)',
            type: 'dashed'
          }
        }
      },
      series: series.map((seriesItem, index) => ({
        name: seriesItem.name || `系列${index + 1}`,
        type: 'line',
        data: seriesItem.data || [],
        symbol: 'circle',
        symbolSize: 6,
        lineStyle: {
          color: currentTheme[0],
          width: 3,
          shadowColor: currentTheme[0],
          shadowBlur: 10
        },
        itemStyle: {
          color: currentTheme[0],
          borderColor: '#0a0e17',
          borderWidth: 2
        },
        areaStyle: seriesItem.areaStyle ? {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: currentTheme[0] + '40'
            }, {
              offset: 1,
              color: currentTheme[1] + '10'
            }]
          }
        } : undefined
      }))
    };
  },

  pie: (data) => {
    const { series = [] } = data;
    const pieData = series[0]?.data || [];
    
    return {
      tooltip: {
        ...tooltipConfig,
        trigger: 'item'
      },
      series: [{
        name: series[0]?.name || '数据',
        type: 'pie',
        radius: ['40%', '65%'],
        center: ['52%', '50%'], // 将饼图稍微向右移动
        avoidLabelOverlap: false,
        itemStyle: {
          borderColor: '#0a0e17',
          borderWidth: 2
        },
        label: {
          color: '#e2e8f0'
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        data: pieData.map((item, index) => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: currentTheme[index % 2 ? 0 : 1]
              }, {
                offset: 1,
                color: currentTheme[index % 2 ? 1 : 0]
              }]
            }
          }
        }))
      }]
    };
  },

  radar: (data) => {
    const { indicators = [], series = [] } = data;
    
    // 处理数据格式
    const radarSeries = series.map((seriesItem, index) => {
      let valueData;
      
      // 处理不同的数据格式
      if (Array.isArray(seriesItem.value)) {
        // 格式1: { value: [num1, num2, ...] }
        valueData = seriesItem.value;
      } else if (Array.isArray(seriesItem.data) && seriesItem.data[0] && Array.isArray(seriesItem.data[0].value)) {
        // 格式2: { data: [{ value: [num1, num2, ...] }] }
        valueData = seriesItem.data[0].value;
      } else if (Array.isArray(seriesItem.data)) {
        // 格式3: { data: [num1, num2, ...] }
        valueData = seriesItem.data;
      } else {
        // 默认空数组
        valueData = [];
      }
      
      return {
        name: seriesItem.name || `系列${index + 1}`,
        type: 'radar',
        data: [{
          value: valueData,
          name: seriesItem.name || `系列${index + 1}`
        }],
        itemStyle: {
          color: currentTheme[0]
        },
        lineStyle: {
          color: currentTheme[0],
          width: 2
        },
        areaStyle: {
          color: {
            type: 'radial',
            x: 0.5,
            y: 0.5,
            r: 0.5,
            colorStops: [{
              offset: 0,
              color: currentTheme[0] + '80'
            }, {
              offset: 1,
              color: currentTheme[1] + '20'
            }]
          }
        }
      };
    });
    
    return {
      tooltip: tooltipConfig,
      radar: {
        shape: 'circle',
        indicator: indicators,
        radius: '65%', // 添加半径设置
        axisName: {
          color: '#94a3b8',
          fontSize: 12
        },
        axisLine: {
          lineStyle: {
            color: 'rgba(79, 172, 254, 0.3)'
          }
        },
        splitLine: {
          lineStyle: {
            color: 'rgba(79, 172, 254, 0.2)'
          }
        },
        splitArea: {
          areaStyle: {
            color: ['rgba(10, 14, 23, 0.3)', 'rgba(10, 14, 23, 0.5)']
          }
        }
      },
      series: radarSeries
    };
  }
};

// 构建图表配置
const buildChartOptions = () => {
  const typeConfig = chartConfigs[props.type]?.(props.data) || chartConfigs.bar(props.data);
  console.log(typeConfig);
  return {
    ...baseOptions,
    ...typeConfig
  };
};

// 初始化或更新图表
const renderChart = () => {
  if (!props.data) return;
  
  const options = buildChartOptions();
  
  if (!isInitialized.value) {
    initChart(options);
  } else {
    updateOptions(options);
  }
};

// 监听数据变化
watch(() => props.data, () => {
  renderChart();
}, { deep: true });

// 监听类型变化
watch(() => props.type, () => {
  renderChart();
});

onMounted(() => {
  nextTick(() => {
    renderChart();
  });
});
</script>

<style lang="scss" scoped>
.tech-chart-container {
  width: 100%;
  height: 100%;
  position: relative;
  background: transparent;
  
  .chart-wrapper {
    width: 100%;
    height: 100%;
  }
  
  .chart-loading {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background: rgba(10, 14, 23, 0.8);
    color: #00f2fe;
    font-size: 14px;
    backdrop-filter: blur(2px);
    
    .loading-spinner {
      width: 30px;
      height: 30px;
      border: 2px solid rgba(0, 242, 254, 0.3);
      border-top: 2px solid #00f2fe;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-bottom: 10px;
    }
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>